function doSearchImTicket() {
	if (!validateBeforeSearch()) {
		return false;
	}
	var filterData = $("#filterForm").serialize();
	$.ajax({
		type:		"POST",
		url:		"../EwhImportDrugMaterial/DoSearchImTicketAjax?set_ajax_view",
		data : filterData,
		dataType:   "json",	
		beforeSend: function() {
		$('div#phaImportLoaderDiv').show();		
	},
	success: 	function(data) {
		if (data.error.code ==  'OK') {
			$("table#imticketTable tbody").html(data.result);			
		} else {
			displayError(data.error.mess);				
		}
		$('div#phaImportLoaderDiv').hide();
	}
	});		

}
function validateBeforeSearch() {
	$('#seachStatusMessage').html('');

	if ($.trim($('#imTicketCodeFilter').val()) == ''
			&& $.trim($('#fromDateFiltermm').val()) == ''
			&& $.trim($('#fromDateFilterFilterdd').val()) == ''
			&& $.trim($('#fromDateFilterFilteryyyy').val()) == ''
			&& $.trim($('#toDateFiltermm').val()) == ''
			&& $.trim($('#toDateFilterdd').val()) == ''
			&& $.trim($('#toDateFilteryyyy').val()) == '')
	{
		$('#seachStatusMessage').html(_("Please enter search condition"));
		return false;
	}

	if (!($.trim($('#fromDateFiltermm').val()) == ''
		&& $.trim($('#fromDateFilterdd').val()) == ''
			&& $.trim($('#fromDateFilteryyyy').val()) == '')) {

		if (!checkDay($('#fromDateFilterdd'),true,'','#seachStatusMessage' )) {
			$('#seachStatusMessage').show();	
			return false;
		}	

		if (!checkMonth($('#fromDateFiltermm'),true,'','#seachStatusMessage')) {
			$('#seachStatusMessage').show();
			return false;
		} 

		var res 	= 	checkDate($('#fromDateFilteryyyy'),
				$('#fromDateFiltermm'),
				$('#fromDateFilterdd'), true, '', '#seachStatusMessage', false);
		if(!res){	
			$('#seachStatusMessage').show();
			return false;
		}
	}


	if (!($.trim($('#toDateFiltermm').val()) == ''
		&& $.trim($('#toDateFilterdd').val()) == ''
			&& $.trim($('#toDateFilteryyyy').val()) == '')) {

		if (!checkDay($('#toDateFilterdd'),true,'','#seachStatusMessage' )) {
			$('#seachStatusMessage').show();	
			return false;
		}	

		if (!checkMonth($('#toDateFiltermm'),true,'','#seachStatusMessage')) {
			$('#seachStatusMessage').show();
			return false;
		} 

		var res 	= 	checkDate($('#toDateFilteryyyy'),
				$('#toDateFiltermm'),
				$('#toDateFilterdd'), true, '', '#seachStatusMessage', false);	

		if(!res){	
			$('#seachStatusMessage').show();
			return false;
		}	
	}

	return true;
}
function removeImTicketRow(imTicketId) {
	$('tr#' + imTicketId).remove();

}
function submitDeleteImticketTB(imTicketId) {

	$.ajax({
		type:		"POST",
		url:		"../EwhImportDrugMaterial/DeleteImTicketAjax?set_ajax_view",
		data : 'imTicketId=' + imTicketId,
		dataType:   "json",	
		beforeSend: function() {
		$('div#phaImportLoaderDiv').show();		
	},
	success: 	function(data) {
		if (data.error.code ==  'OK') {
			removeImTicketRow(imTicketId);
		} else {
			displayError(data.error.mess);				
		}
		$('div#phaImportLoaderDiv').hide();
	}
	});	


}
function deleteImTicketTB(imTicketId) {
	if (imTicketId != null && $.trim(imTicketId) != '') {
		var c = $($('tr#' + imTicketId ).children()[1]);
		var text = c.text();
		promptConfirm(_("Delete"),_('Are you sure to delete this import ticket[{0}]?', text), function() {
			submitDeleteImticketTB(imTicketId); 
			return true;
		},'YesNo','warn',_('No'));
	}
}




function submitDeleteImticketCP(imTicketId) {

	$.ajax({
		type:		"POST",
		url:		"../EwhImportDrugMaterial/DeleteImTicketAjax?set_ajax_view",
		data : 'imTicketId=' + imTicketId,
		dataType:   "json",	
		beforeSend: function() {
		$('div#phaImportLoaderDiv').show();		
	},
	success: 	function(data) {
		if (data.error.code ==  'OK') {
			//show search page, hide edit page
			removeImTicketRow(imTicketId);
			$('div#searchDiv').show();
			$('div#actionResultArea').html('');
			$('div#actionResultArea').hide();
			
			
		} else {
			displayError(data.error.mess);				
		}
		$('div#phaImportLoaderDiv').hide();
	}
	});	


}
function deleteImTicketCP(imTicketId) {
	if (imTicketId != null && $.trim(imTicketId) != '') {
		promptConfirm(_("Delete"),_('Are you sure to delete this import ticket?'), function() {
			submitDeleteImticketCP(imTicketId); 
			return true;
		},'YesNo','warn',_('No'));
	}
}


function editImTicket(imTicketId) {
	$.ajax({
		type:		"POST",
		url:		"../EwhImportDrugMaterial/EditImTicketAjax?set_ajax_view",
		data : 'imTicketId=' + imTicketId,
		dataType:   "json",	
		beforeSend: function() {
		$('div#phaImportLoaderDiv').show();		
	},
	success: 	function(data) {
		if (data.error.code ==  'OK') {
			//show edit page, hide search page
			$('div#searchDiv').hide();
			$('div#actionResultArea').html(data.result);
			$('div#actionResultArea').show();
		} else {
			displayError(data.error.mess);				
		}
		$('div#phaImportLoaderDiv').hide();
	}
	});

}



function checkAndDisableItemTypeSel() {	
	
	if ($('#addedDrugMaterialTable tbody').children().length == 0) {
		$("select#selItemType").attr('disabled','');
	} else {
		$("select#selItemType").attr('disabled','disabled');		
	}	
}



function doAddDrugMaterial(drugMaterialId) {
	var lcInt = locale(decimalPoint, thousandSep, 0);	
	var nameDateExpP0Hidden = 'addedDateExpHidden' + dateFormatPart0;
	var nameDateExpP1Hidden = 'addedDateExpHidden' + dateFormatPart1;
	var nameDateExpP2Hidden = 'addedDateExpHidden' + dateFormatPart2;
	var imTicketId = $('#imticketId').val();
	var qty = parseLcNum($('#inputDMQty').val(), lcInt);
	var unitPrice = parseLcNum($('#inputDMUnitPrice').val(), lcInt);
	var addedDMId = parseInt($('input#addedDMCount').val());
	var addedRow = '';
	addedRow += '<tr id="addedDM' + addedDMId + '">';
	addedRow += '<td style="width: 30px;">&nbsp;</td>';
	addedRow += '<td style="width: 200px;"><div style="width: 200px;white-space: normal;">' + $("#inputDMName").val() + '</div>'
				+ '<input name="addedInputDMNameHidden" type="hidden" value="' + $("input#inputDMNameHidden").val() + '">' 
				+ '</td>';
	
	addedRow += '<td style="width: 75px;"><div style="width: 75px;white-space: normal;">' 
		+ $("#inputDMLot").val() + '</div>'
		+ '<input name="addedinputDMLotHidden" type="hidden" value="' + $("inputDMLot").val() + '">'		
		+ '</td>';
	
	addedRow += '<td style="width: 75px;"><div style="width: 75px;white-space: normal;">' 
	+ toLcString(qty, lcInt) + '</div>'
	+ '<input name="addedinputDMQtyHidden" type="hidden" value="' + qty + '">'		
	+ '</td>';
	
	addedRow += '<td style="width: 75px;"><div style="width: 75px;white-space: normal;">' 
		+ $("span#inputDMUnit").html() 
		+ "</div>"
		+ '<input name="addedUnitHidden" type="hidden" value="' + $("input#inputDMUnitHidden").val() + '">' 
		+ '</td>';
	
	addedRow += '<td style="width: 145px;"><div style="width: 145px;white-space: normal;">'
		+ _("{0}/{1}/{2}", $("#dateExp" + dateFormatPart0).val(), 
			$("#dateExp" + dateFormatPart1).val(),
			$("#dateExp" + dateFormatPart2).val())
		+ "</div>"
		+ '<input name="' + nameDateExpP0Hidden + '"  type="hidden" value="' + $("#dateExp" + dateFormatPart0).val() + '">'
		+ '<input name="' + nameDateExpP1Hidden + '"  type="hidden" value="' + $("#dateExp" + dateFormatPart1).val() + '">'
		+ '<input name="' + nameDateExpP2Hidden + '"  type="hidden" value="' + $("#dateExp" + dateFormatPart2).val() + '">'
		+ '</td>';
	
	addedRow += '<td style="width: 100px;"><div style="width: 100px;white-space: normal;">' 
	+ toLcString(unitPrice, lcInt) + '</div>'
	+ '<input name="addedinputDMUnitPriceHidden" type="hidden" value="' + unitPrice + '">'		
	+ '</td>';
	addedRow += '<td style="width: 100px;"><div style="width: 100px;white-space: normal;">' 
		+ toLcString(unitPrice * qty,lcInt) + '</div>'
		+ '</td>';
	addedRow += '<td style="border-right: none;"><a href="javascript:removeDrugMaterialRow(\'addedDM' 
		+ addedDMId 
		+ '\', \''
		+ imTicketId
		+ '\', \'' 
		+ drugMaterialId 
		+ '\');"><img alt="" src="../images/remove_small.png"></a> </td>';
	
	addedRow += '</tr>';
	$('#addedDrugMaterialTable tbody').prepend(addedRow);
	checkAndDisableItemTypeSel();
	//keep count row
	$('input#addedDMCount').val(addedDMId + 1);
	//reset input field
	resetInputDrugMaterialField();
}
function addDrugMaterialRow() {
	$('#statusMessage').html('');
	var drugMaterialId = $("#inputDMNameHidden").val();
	var itemType = $("select#selItemType").val();
	var drugMaterialName = $("#inputDMName").val();
	var imTicketId = $('#imticketId').val();
	
	if (drugMaterialId == null || $.trim(drugMaterialId) == ''
		|| drugMaterialName == null || $.trim(drugMaterialName) == '') {
		showMessage('statusMessage', _('Drug/material empty'), 'error');
		$('#inputDMName').focus();
		return;
		
	}
	 
	 $.ajax({
		type:		"POST",
		url:		"../EwhImportDrugMaterial/ValidateDrugMaterialAjax?set_ajax_view",
		data: 'imTicketId=' + imTicketId
		  	  + "&drugMaterialId=" + drugMaterialId
			  + "&enumItemType=" + itemType
			  + "&drugMaterialInputedName=" + drugMaterialName
			  ,
		dataType:   "json",
		beforeSend: function() {
			showMessage('statusMessage', '', 'success');		
		},
		success: 	function(data) {
			
			if (data.error.code !=  'OK' && data.error.code != 'PHA_003') {				
				showMessage('statusMessage', data.error.mess, 'error');	
				return false;
			} else {
				//duplicate
				if (data.error.code == 'PHA_003') {
					promptConfirm(_("Duplicate"),_('This drug/material [{0}] is duplicated. Do you want to add it?',
							drugMaterialName), function() {
						validateAndAddDM(); 
						return true;
					},'YesNo','warn',_('No'));
					
				} else {
					validateAndAddDM();
				}
				
			}
			
		}
	});
	
}

function validateAndAddDM() {
	
	var lcInt = locale(decimalPoint, thousandSep, 0);
	
	if (!validateNumberByLocal($('#inputDMQty'), lcInt, true, '' , 'statusMessage')) {
		return false;
	}
	
	if (!checkIntMinMax('inputDMQty', 1, 10000, 'statusMessage',
			_("The quantity must between {0} and {1}",1,10000))) {
		return false;
	}
	if (!checkDay($('#dateExpdd'),true,'','#statusMessage' )) {
			$('#statusMessage').show();	
			return false;
	}	
		
	if (!checkMonth($('#dateExpmm'),true,'','#statusMessage')) {
		$('#statusMessage').show();
		return false;
	} 

	var res 	= 	checkDateEx($('#dateExpyyyy'),
			$('#dateExpmm'),
			$('#dateExpdd'), true,'', '#statusMessage', true, 'gt');	
	

	if(!res){	
		$('#statusMessage').show();
		return false;
	}
	
	if (!validateNumberByLocal($('#inputDMUnitPrice'), lcInt, true, '' , 'statusMessage')) {
		return false;
	}
	
	if (!checkIntGt('inputDMUnitPrice', 0, 'statusMessage',
			_("The unit price must greater than {0}",0))) {
		return false;
	}
	$('#inputDMName').focus();
	submitAddDrugMaterial();
}
function submitAddDrugMaterial() {
	var data = buildDrugMaterialData();
	
	$.ajax({
		type:		"POST",
		url:		"../EwhImportDrugMaterial/AddDrugMaterialAjax?set_ajax_view",
		data: data,
		dataType:   "json",
		success: 	function(data) {
			if (data.error.code ==  'OK') {
				doAddDrugMaterial(data.result);				
			} else if (data.error.code = 'PHA_003') {
				displayError(data.error.mess);				
				doAddDrugMaterial(data.result);
			} else {
				displayError(data.error.mess);					
			}
			
		}
	});
}

function resetInputDrugMaterialField() {
	$("#inputDMName").val('');
	$("#inputDMName").select();
	$("#inputDMNameHidden").val('');
	$("#inputDMLot").val('');
	$("#inputDMQty").val('');	
	$("#inputDMUnit").html('');
	$("#inputDMUnitHidden").val('');
	$("#dateExpdd").val('');
	$("#dateExpmm").val('');
	$("#dateExpyyyy").val('');
	$("#inputDMUnitPrice").val('');	
}
function resetImportTicketForm() {
	$('#imticketId').val('');
	$('#imticketCode').val('');
	$('#ImTicketCodeText').html('');
	$("#datedd").val('');
	$("#datemm").val('');
	$("#dateyyyy").val('');
	$('#userNameText').html('');
	$('#note').val('');
	$("#inputDMName").val('');
	$("#inputDMNameHidden").val('');
	$("#inputDMUnitHidden").val('');
	$("#inputDMLot").val('');
	$("#inputDMQty").val('');
	$("#dateExpdd").val('');
	$("#dateExpmm").val('');
	$("#dateExpyyyy").val('');
	addDatePicker("#datedd",'#datemm','#dateyyyy',false,false,true);
	$("#inputDMUnitPrice").val('');
	$("div#addDrugMaterialBtn").hide();		
	//$("#saveImTicketBnt").attr('disabled','disabled');
	$('table#addedDrugMaterialTable tbody').html('');
	$('#statusMessage').html('');
	$('#statusMessageImTicket').html('');
	$('#savingStatusMessage').html('');
	$('select#selProvider').val('');
	$('select#selVat').val('5');
	$("span#imticketCodeText").html('');
	
}

function submitRemoveDrugMaterialRow(rowId, imTicketId, addedDrugMaterialId) {
	
	if (addedDrugMaterialId != null) {
		$.ajax({
			type:		"POST",
			url:		"../EwhImportDrugMaterial/DeleteDrugMaterialAjax?set_ajax_view",
			data: "imTicketId=" + imTicketId
		 	+ "&addedDrugMaterialId=" + addedDrugMaterialId,
			dataType:   "json",
			success: 	function(data) {
				if (data.error.code ==  'OK') {
					$('#' + rowId).remove();
					checkAndDisableItemTypeSel();				
				} else {
					displayError(data.error.mess);				
				}
				
			}
		});		
		
	} else {
	
		$('#' + rowId).remove();
		checkAndDisableItemTypeSel();
	}

}

function removeDrugMaterialRow(rowId, imTicketId, addedDrugMaterialId) {
	var c = $($('#' + rowId ).children()[1]);
	var text = c.text();
	promptConfirm(_("Delete"),_('Are you sure to delete this item [{0}]?', text), function() {
		submitRemoveDrugMaterialRow(rowId, imTicketId, addedDrugMaterialId); 
		return true;
	},'YesNo','warn',_('No'));	
}


/**
 * validate before add drug/material
 */
function validateBeforeAddDrugMaterial() {
	
	
	$('#statusMessage').html('');
	var drugMaterialId = $("#inputDMNameHidden").val();
	var itemType = $("select#selItemType").val();
	var drugMaterialName = $("#inputDMName").val();
	
	if (drugMaterialId == null || $.trim(drugMaterialId) == ''
		|| drugMaterialName == null || $.trim(drugMaterialName) == '') {
		showMessage('statusMessage', _('Drug/material empty'), 'error');
		return false;
		
	}
	 
	 $.ajax({
		type:		"POST",
		url:		"../EwhImportDrugMaterial/ValidateDrugMaterialAjax?set_ajax_view",
		data: "drugMaterialId=" + drugMaterialId
			  + "&enumItemType=" + itemType
			  + "&drugMaterialInputedName=" + drugMaterialName
			  ,
		dataType:   "json",
		beforeSend: function() {
			showMessage('statusMessage', '', 'success');		
		},
		success: 	function(data) {
			
			if (data.error.code !=  'OK') {				
				showMessage('statusMessage', data.error.mess, 'error');	
				return false;
			} else {
				if (!checkIntMinMax('inputDMQty', 1, 10000, 'statusMessage',
						_("The quantity must between {0} and {1}",1,10000))) {
					return false;
				}
				if (!checkDay($('#dateExpdd'),true,'','#statusMessage' )) {
						$('#statusMessage').show();	
						return false;
				}	
					
				if (!checkMonth($('#dateExpmm'),true,'','#statusMessage')) {
					$('#statusMessage').show();
					return false;
				} 

				var res 	= 	checkDate($('#dateExpyyyy'),
						$('#dateExpmm'),
						$('#dateExpdd'), true, '', '#statusMessage', false);	

				if(!res){	
					$('#statusMessage').show();
					return false;
				}
				
				if (!checkIntGt('inputDMUnitPrice', 0, 'statusMessage',
						_("The unit price must greater than {0}",0))) {
					return false;
				}
				return true;
				
			}
			
		}
	});	
	 
	
}
 
function validateBeforeSaveImTicket() {
	$('#statusMessageImTicket').html('');
	
	if (!checkDay($('#datedd'),true,'','#statusMessageImTicket' )) {
			$('#statusMessageImTicket').show();	
			return false;
	}	
		
	if (!checkMonth($('#datemm'),true,'','#statusMessageImTicket')) {
		$('#statusMessageImTicket').show();
		return false;
	} 

	var res 	= 	checkDate($('#dateyyyy'),
			$('#datemm'),
			$('#datedd'), true, '', '#statusMessageImTicket', false);	

	if(!res){	
		$('#statusMessageImTicket').show();
		return false;
	}
	
	if (!validateSelectBox('selProvider',_('Please select provider'),
	'statusMessageImTicket')) {
		return false;
	}
	
	
	return true;
}
function buildImTicketData() {
	
	var imTicketId = $('#imticketId').val();
	var d = new Date();
	var currHour = (d.getHours() < 10 ? '0' + d.getHours(): d.getHours());
	var currMin = (d.getMinutes() < 10 ? '0' + d.getMinutes(): d.getMinutes());
	var currSeconds = (d.getSeconds() < 10 ? '0' + d.getSeconds(): d.getSeconds());


	var date = $('#dateyyyy').val() 
		+ '-' 
		+ $('#datemm').val()
		+ '-'
		+ $('#datedd').val()
		+ ' '
		+ currHour
		+ ':'
		+ currMin
		+ ':'
		+ currSeconds;
	var itemType = $('select#selItemType :selected').val();
	var providerId = $('select#selProvider :selected').val();
	var vat = $('select#selVat :selected').val();
	var note = $('#note').val();
	
	var data = "imTicketId=" + imTicketId
	 	+ "&date=" + date
	 	+ "&enumItemType=" + itemType
	 	+ "&providerId=" + providerId	 	
	 	+ "&vat=" + vat
		+ "&note=" + note;
	 
	return data;
}

function saveImTicket() {
	if (!validateBeforeSaveImTicket()) {
		return false;
	}
	var data = buildImTicketData();	
	var url = '';
	var imTicketId = $('#imticketId').val();
	if (imTicketId == null || $.trim(imTicketId) == '') {
		url = "../EwhImportDrugMaterial/CreateImTicketAjax?set_ajax_view";
		
	} else {
		url = "../EwhImportDrugMaterial/SaveImTicketAjax?set_ajax_view";
	}
	
	$.ajax({
		type:		"POST",
		url:		url,
		data: data,		
		dataType:   "json",
		beforeSend: function() {
			showMessage('savingStatusMessage', '', 'success');		
		},
		success: 	function(data) {
			if (data.error.code ==  'OK') {
				$("span#imticketCodeText").html(data.result.code)
				$("input#imticketCode").val(data.result.code);
				$("input#imticketId").val(data.result.id);	            
				enableAdding(true);
				showMessage('savingStatusMessage', _('Save successful'), 'success');
								
			} else {
				enableAdding(false);
				displayError(data.error.mess);				
			}
			
		}
	});		
	
}


function enableAdding(status) {
		
	if (status == true) {		
		$("#inputDMName").attr('disabled','');		
		$("#inputDMLot").attr('disabled','');
		$("#inputDMQty").attr('disabled','');
		$("#dateExpdd").attr('disabled','');
		$("#dateExpmm").attr('disabled','');
		$("#dateExpyyyy").attr('disabled','');
		$("#inputDMUnitPrice").attr('disabled','');	
		$("div#addDrugMaterialBtn").show();		
		//$("#saveImTicketBnt").attr('disabled','');
	} else {
		
		$("#inputDMName").attr('disabled','disabled');		
		$("#inputDMLot").attr('disabled','disabled');
		$("#inputDMQty").attr('disabled','disabled');
		$("#dateExpdd").attr('disabled','disabled');
		$("#dateExpmm").attr('disabled','disabled');
		$("#dateExpyyyy").attr('disabled','disabled');
		$("#inputDMUnitPrice").attr('disabled','disabled');
		//$("#saveImTicketBnt").attr('disabled','disabled');		
		$("div#addDrugMaterialBtn").hide();
		
	}
}
 
function buildDrugMaterialData() {
	var imTicketId = $('#imticketId').val();
	var drugMaterialId = $("#inputDMNameHidden").val();
	var itemType = $("select#selItemType").val();
	var drugMaterialName = $("#inputDMName").val();
	var lot = $("input#inputDMLot").val();
	var lcInt = locale(decimalPoint, thousandSep, 0);	
	var qty = parseLcNum($('#inputDMQty').val(), lcInt);
	var unitPrice = parseLcNum($('#inputDMUnitPrice').val(), lcInt);
	var date = $('#dateExpyyyy').val() 
		+ '-' 
		+ $('#dateExpmm').val()
		+ '-'
		+ $('#dateExpdd').val()
		+ ' 00:00:00';
	var data = "imTicketId=" + imTicketId
	 	+ "&drugMaterialId=" + drugMaterialId
	 	+ "&enumItemType=" + itemType
	 	+ "&drugMaterialInputedName=" + drugMaterialName
	 	+ "&lot=" + lot
	 	+ "&quantity=" + qty
	 	+ "&expiredDate=" + date
	 	+ "&unitPrice=" + unitPrice;	 	
	 	
	 
	return data;
}
